/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kylingroup.Desktop.Utils;

import com.kylingroup.Desktop.Bean.Bean_Plugin;
import com.kylingroup.Desktop.DAO.Dao_Plugin;
import com.kylingroup.Desktop.Database.DBConnection;
import com.kylingroup.Desktop.MainFrame;
import com.kylingroup.Desktop.MainFrameController;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.dom4j.Element;

/**
 *
 * @author kylin
 */
public class Installer {
    private String extractdir=System.getProperty("user.dir");
    private Extractor extractortask;
    public Installer(Stage stage,MainFrameController controller){
        FileChooser filechooser=new FileChooser();
        filechooser.setTitle("Select Plugin");
        filechooser.setInitialDirectory(new File(System.getProperty("user.dir")));
        filechooser.getExtensionFilters().addAll(
            new FileChooser.ExtensionFilter("ZIP", "*.zip"),
            new FileChooser.ExtensionFilter("RAR", "*.rar"),
            new FileChooser.ExtensionFilter("TAR", "*.tar.gz")
        );      
        File file=filechooser.showOpenDialog(stage);
        if(file!=null){
            extract(file,controller);
        }
    }
    public void extract(File file,MainFrameController controller){
        long size=file.length();
        int m=1024*1024;
        int g=m*1024;
        int buffersize=0;
        int sleep=10;
        if(size<m){
            buffersize=1024;
        }else if(size>m&&size<g){
            buffersize=m*15;
        }
        extractortask=new Extractor(file,extractdir,buffersize,sleep);
        extractortask.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED,
            new EventHandler<WorkerStateEvent>(){
            @Override
            public void handle(WorkerStateEvent event) {
                HashMap<String,String> info=extractortask.getValue();

                File jarfile=null;
                File xmlfile=null;
                File f=new File(info.get("extractdir")+"/");
                File files[]=f.listFiles();
                for(int i=0;i<files.length;i++){
                    String filename=files[i].getAbsolutePath();
                    if(filename.contains(".jar")){
                        jarfile=files[i];
                    }else if(filename.contains(".xml")){
                        xmlfile=files[i];
                    }
                }

                PluginWriter writer=new PluginWriter();

                writer.setXml(xmlfile);
                Element root=writer.getRoot();
                List list=writer.getPlugins(root);
                Iterator itor=list.iterator();
                
                while(itor.hasNext()){
                    Bean_Plugin p=(Bean_Plugin)itor.next();
                    p.setLocation(jarfile.getPath());
                    if(!record(p)){
                        break;
                    }else{
                        System.out.println("record success!");
                    }
                }
                
                updateUI(controller,"Info:Succes",false);
            } 
        });
        
        updateUI(controller,"Info:Extracting-",true);

        new Thread(extractortask).start();
    }
    public void updateUI(MainFrameController controller,String info,boolean visible){
        controller.info.setText(info);
        if(visible){
            controller.progressbar.setVisible(true);
            controller.progressbar.setProgress(0);
            controller.progressbar.progressProperty().bind(extractortask.progressProperty());
        }else{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Installer.class.getName()).log(Level.SEVERE, null, ex);
            }
            controller.progressbar.progressProperty().unbind();
            controller.progressbar.setVisible(false);
        }
    }
    private boolean record(Bean_Plugin b){
        boolean result=false;
        DBConnection dbconn=MainFrame.dbconn;
        Dao_Plugin dao=new Dao_Plugin();
        dao.setConnection(dbconn);
        if(dao.add(b)){
            result=true;
        }else{
            result=false;
        }
        return result;
    }
}
